/* Copyright (c) 2008 LepomisLab.com, Andrey Turkin
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#ifndef MultiBindHelper_H_
#define MultiBindHelper_H_

#include "wx/wxprec.h"

#ifndef WX_PRECOMP
    #include "wx/wx.h"
#endif

#include "NSArray.h"

class MultiBindHelper
{
public:
	MultiBindHelper(const wxString& prefix) : m_prefix(prefix)
	{
		m_values = new NSArray();
	}

	bool onBind(const wxString& key, wxString& new_binding)
	{
		size_t pos;
		if (!get_pos(key, pos))
			return false;
		wxCHECK(pos <= m_values->length(), false);
		if (pos < m_values->length())
			return false;
		m_values->addObject(NULL);
		new_binding = m_prefix;
		new_binding << (unsigned int)m_values->length();
		return true;
	}

	bool setValue(const wxString& key, wxObject* value)
	{
		size_t pos;
		if (!get_pos(key, pos))
			return false;
		wxCHECK(pos < m_values->length(), false);
		m_values->setObject(pos, value);
		return true;
	}

	bool getValue(const wxString& key, wxObject* &value)
	{
		size_t pos;
		if (!get_pos(key, pos))
			return false;
		wxCHECK(pos < m_values->length(), false);
		value = m_values->getObject(pos);
		return true;
	}

	NSArray* getValues() {return m_values;}

private:
	bool get_pos(const wxString& key, size_t& pos)
	{
		long p = 0;
		wxString rest;
		if (key.StartsWith(key, &rest) && (rest.empty() || rest.ToLong(&p)))
		{
			pos = (size_t)p;
			return true;
		}
		return false;
	}

	wxString m_prefix;
	NSArray* m_values;
};

class MultiArrayBindHelper : public MultiBindHelper
{
public:
	MultiArrayBindHelper(const wxString& prefix) : MultiBindHelper(prefix)
	{
	}
};

#endif